package com.cy.aircompressor.utils;

import java.security.MessageDigest;

public class MD5 {
    /**
     * MD5加密之方法二 * @explain java实现 * @param str * 待加密字符串 * @return 16进制加密字符串
     */
    public static String encrypt2ToMD5(String str) {

        // 加密后的16进制字符串
        String hexStr = "";
        try {

            // 此 MessageDigest 类为应用程序提供信息摘要算法的功能
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            // 转换为MD5码
            byte[] digest = md5.digest(str.getBytes("utf-8"));
            hexStr = toHex(digest);
        } catch (Exception e) {

            e.printStackTrace();
        }
        return hexStr;
    }

    /**
     * byte[] -&gt; hex
     *
     * @param bytes byte array src
     * @return Hex's String
     */
    private static String toHex(byte... bytes) {
        if (bytes == null) return "";

        int len = bytes.length;
        StringBuffer sw = new StringBuffer(len * 2);
        for (int i = 0; i < len; ++i) {
            sw.append(toHexDigit(bytes[i] >> 4 & 0x0f));
            sw.append(toHexDigit(bytes[i] & 0x0f));
        }
        return sw.toString();
    }

    private static char toHexDigit(int i) {
        if (i <= 9) {
            return (char) (i + 0x30);
        } else {
            return (char) (i + 0x57);
        }
    }
}
